package com.hf.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.hf.config.JwtConfig;
import com.hf.entity.Users;
import com.hf.mapper.UsersMapper;
import com.hf.service.IUsersService;

@RestController
public class LoginController {
	@Autowired
	IUsersService iUsersService;

	@Autowired
	private JwtConfig jwtConfig;

	@PostMapping("/login")
	public Object userLogin(@RequestParam String loginName, @RequestParam String password) {
		Users user = iUsersService.userLogin(loginName);
		System.out.println("登录名称：" + loginName);
		System.out.println("登录名称：" + password);

		// 时间=
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		// 声明map集合
		Map<String, Object> map = new HashMap<>();

		if (user == null) {
			map.put("code", 1);
			map.put("msg", "该账号不存在");
		} else {
			if (user != null && user.getPassword().equals(password) && user.getIsLockOut() == 0) {
				// 账户最后登录时间
				// user.setLastLoginTime(sdf.format(date));
				boolean updateLastLoginTime = iUsersService.updateLastLoginTime(user.getId(), sdf.format(date));
				System.out.println("最后登录时间" + sdf.format(date));

				// 省略数据源校验
				String token = jwtConfig.getToken(loginName + password);
				if (!StringUtils.isEmpty(token)) {
					map.put("token", token);
				}
				map.put("code", 0);
				map.put("msg", "登录成功");
				map.put("data", user);
				System.out.println("登录信息：" + user);
			} else if (user.getPsdWrongNum() == 2) {
				boolean res = iUsersService.updatelockNum(user.getLoginName());
				// 账号锁定时间
				boolean setLockTime = iUsersService.setLockTime(sdf.format(date), user.getId());
				if (res) {
					map.put("code", 1);
					map.put("msg", "密码错误，账号被锁定");
				} else {
					map.put("code", 1);
					map.put("msg", "登录失败");
				}
			} else if (user.getIsLockOut() == 1) {
				iUsersService.updatepsdWrongNum(loginName);
				map.put("code", 1);
				map.put("msg", "账号已被锁定");
			} else if (!user.getPassword().equals(password)) {
				iUsersService.updatepsdWrongNum(loginName);
				map.put("code", 1);
				map.put("msg", "密码错误");
			}

		}
		return map;
	}

}
